package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.Group;
import com.cfets.annualAssessment.entity.GroupMember;
import com.cfets.annualAssessment.entity.TableContainer;
import com.cfets.annualAssessment.service.GroupService;
import com.cfets.annualAssessment.util.CheckUtil;
import com.cfets.annualAssessment.util.ExcelUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by ShenYiChou on 2017/2/2.
 */
@Controller
@RequestMapping("/admin/group")
public class GroupController {
    @Autowired
    private GroupService groupService;

    @RequestMapping("/index")
    public String index(Model model){
        return "group";
    }

    @RequestMapping(value = "/Get",method = RequestMethod.POST)
    public ResponseEntity<?> groupList(Group group){
        List<Group> groupList = groupService.getGroupPage(group);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(groupList);
        tableContainer.setiTotalDisplayRecords(group.getTotalCount());
        tableContainer.setiTotalRecords(group.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }

    @RequestMapping(value = "/restful/Get",method = RequestMethod.POST)
    public ResponseEntity<?> groupMemList(Group group){
        List<GroupMember> groupMembers = groupService.getGroupMemPage(group);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(groupMembers);
        tableContainer.setiTotalDisplayRecords(group.getTotalCount());
        tableContainer.setiTotalRecords(group.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<?> createOrUpdate(@Valid Group group, BindingResult result) {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
        List<Group> groups=null;
        //-1：群组名重复标志位
        groups = this.groupService.GroupList(group);
        if(!groups.isEmpty()){
            return new ResponseEntity<>(-1, HttpStatus.OK);
        }
        boolean flag;
        if(group.getId()!=null && group.getId()!=0){
            flag = this.groupService.updateGroup(group);
        }else {
            flag = this.groupService.newGroup(group);
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteGroup(@PathVariable("id") int id){
        boolean flag1 = this.groupService.deleteGroup(id);
        boolean flag = this.groupService.deleteGroupById(id);
        if (!flag1){
            flag = false;
        }

        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @RequestMapping(value = "/import",method = RequestMethod.POST)
    public ResponseEntity<?> importExcel(MultipartFile groupFile) {
        try {
            Workbook xwb = WorkbookFactory.create(groupFile.getInputStream());
            Sheet sheet = xwb.getSheetAt(0);
            Row row;
            for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) {
                if (i == 0) {
                    continue;
                }
                boolean flag = false;
                row = sheet.getRow(i);
                if(Objects.equals(row.getCell(1).toString(), "")||Objects.equals(row.getCell(2).toString(), "")
                        ||Objects.equals(row.getCell(3).toString(), "")){
                    return new ResponseEntity<>(false, HttpStatus.OK);//群值为空
                }
                Group group = new Group();
                group.setGroup_name(row.getCell(1).toString());
                if(this.groupService.GroupList(group).isEmpty()) {
                    return new ResponseEntity<>(-1, HttpStatus.OK);//群值名不存在
                }
                this.groupService.deleteGroupMember(row.getCell(1).toString());
                GroupMember groupMember = new GroupMember();
                groupMember.setGroup_name(row.getCell(1).toString());
                groupMember.setName(row.getCell(2).toString());
                groupMember.setMobile(row.getCell(3).toString());
                groupMember.setE_mail(row.getCell(4)!=null?row.getCell(4).toString():"");
                groupMember.setWechat_num(row.getCell(5)!=null?row.getCell(5).toString():"");
                groupMember.setOrg_name(row.getCell(6)!=null?row.getCell(6).toString():"");
                groupMember.setDepartment(row.getCell(7)!=null?row.getCell(7).toString():"");
                groupMember.setDuty(row.getCell(8)!=null?row.getCell(8).toString():"");
                this.groupService.newGroupMem(groupMember);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        return new ResponseEntity<>(true, HttpStatus.OK);
    }
    @RequestMapping("/exportEmail")
    public String exportEmail(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String[] item;
        if(CheckUtil.isEmpty(request.getParameter("groups"))){
            return null;
        }
        item = URLDecoder.decode(request.getParameter("groups"),"UTF-8").split(",");
        List<GroupMember> groupMembers = new ArrayList<>();
        for(String group:item) {
            Group newgroup = new Group();
            newgroup.setGroup_name(group);
            List<GroupMember> groupMemberList = groupService.GroupMemberList(newgroup);
            if(!groupMemberList.isEmpty()) {
                groupMembers.addAll(groupMemberList);
            }
        }
        if(!groupMembers.isEmpty()) {
            ExcelUtil.exportExcel("群组", new String[]{"NO.", "群组", "姓名", "手机", "E_mail", "微信号", "机构名称", "部门", "职务"},
                    new String[]{"", "group_name", "name", "mobile", "e_mail", "wechat_num", "org_name", "department", "duty"},
                    groupMembers, response);
        }
        return null;
    }
}
